#!/bin/bash

set -e

echo "=========================================="
echo "部署Lambda函数和API Gateway（使用Docker）"
echo "=========================================="

LAMBDA_DIR="$(dirname "$0")/../lambda"
TEMP_DIR="/tmp/browse-etl-lambda"
DEPS_CACHE_DIR="/tmp/browse-etl-lambda-deps"
REQUIREMENTS_HASH=$(md5 -q "$LAMBDA_DIR/requirements.txt" 2>/dev/null || md5sum "$LAMBDA_DIR/requirements.txt" | cut -d' ' -f1)

# 创建临时目录
rm -rf "$TEMP_DIR"
mkdir -p "$TEMP_DIR"

# 复制Lambda代码
echo "📦 打包Lambda函数..."
cp -r "$LAMBDA_DIR"/* "$TEMP_DIR/"

# 检查依赖缓存
cd "$TEMP_DIR"
CACHE_MARKER="$DEPS_CACHE_DIR/$REQUIREMENTS_HASH/.cache_complete"

if [ -f "$CACHE_MARKER" ]; then
    echo "✅ 使用缓存的依赖（hash: ${REQUIREMENTS_HASH:0:8}...）"
    # 复制缓存的依赖包
    cd "$DEPS_CACHE_DIR/$REQUIREMENTS_HASH"
    for item in *; do
        if [ "$item" != "handler.py" ] && [ "$item" != "requirements.txt" ]; then
            cp -r "$item" "$TEMP_DIR/"
        fi
    done
    cd "$TEMP_DIR"
else
    echo "📥 安装依赖（首次或依赖已变更）..."
    pip3 install -r requirements.txt -t . --upgrade
    
    # 缓存依赖包
    echo "💾 缓存依赖..."
    mkdir -p "$DEPS_CACHE_DIR/$REQUIREMENTS_HASH"
    for item in *; do
        if [ "$item" != "handler.py" ] && [ "$item" != "requirements.txt" ] && [ "$item" != "function.zip" ]; then
            cp -r "$item" "$DEPS_CACHE_DIR/$REQUIREMENTS_HASH/"
        fi
    done
    touch "$CACHE_MARKER"
    echo "✅ 依赖已缓存"
fi

# 创建部署包
echo "🗜️  创建部署包..."
zip -r function.zip . -q

# 将zip文件复制到可访问的位置
cp function.zip /tmp/lambda-function.zip

echo "☁️  部署到LocalStack（通过Docker）..."

# 首先创建 Kinesis Stream（如果不存在）
echo "🌊 检查并创建 Kinesis Stream..."
STREAM_EXISTS=$(docker exec browse-etl-localstack awslocal kinesis list-streams --region us-east-1 --query "StreamNames[?@=='click-events-stream']" --output text 2>/dev/null || echo "")

if [ -z "$STREAM_EXISTS" ]; then
    echo "📝 创建 Kinesis Stream: click-events-stream..."
    docker exec browse-etl-localstack awslocal kinesis create-stream \
        --stream-name click-events-stream \
        --shard-count 1 \
        --region us-east-1 2>/dev/null || echo "   Stream 可能已存在"

    # LocalStack 的 Stream 通常立即 ACTIVE，无需等待
    echo "✅ Kinesis Stream 已创建（LocalStack 无需等待激活）"
else
    echo "✅ Kinesis Stream 已存在"
fi

# 使用docker cp将文件复制到容器
docker cp /tmp/lambda-function.zip browse-etl-localstack:/tmp/function.zip

# 在LocalStack容器内执行AWS命令
echo "📤 创建Lambda函数..."
docker exec browse-etl-localstack bash -c "
  awslocal lambda create-function \
    --function-name click-event-handler \
    --runtime python3.12 \
    --handler handler.lambda_handler \
    --zip-file fileb:///tmp/function.zip \
    --role arn:aws:iam::000000000000:role/LambdaExecutionRole \
    --environment Variables='{AWS_ENDPOINT=http://localstack:4566,AWS_REGION=us-east-1,KINESIS_STREAM_NAME=click-events-stream}' \
    --timeout 30 \
    --memory-size 256 \
    --region us-east-1 2>/dev/null || \
  awslocal lambda update-function-code \
    --function-name click-event-handler \
    --zip-file fileb:///tmp/function.zip \
    --region us-east-1
"

echo "✅ Lambda函数已部署"

# 创建API Gateway
echo "🌐 创建API Gateway..."

# 检查API是否已存在
API_ID=$(docker exec browse-etl-localstack awslocal apigateway get-rest-apis --query "items[?name=='events-api'].id" --output text 2>/dev/null || echo "")

if [ -z "$API_ID" ]; then
  # 创建新API
  API_ID=$(docker exec browse-etl-localstack awslocal apigateway create-rest-api \
    --name events-api \
    --description "Click Events API" \
    --region us-east-1 \
    --query 'id' --output text)
  echo "✅ 创建API: $API_ID"
else
  echo "✅ 使用现有API: $API_ID"
fi

# 获取根资源ID
ROOT_RESOURCE_ID=$(docker exec browse-etl-localstack awslocal apigateway get-resources \
  --rest-api-id "$API_ID" \
  --query 'items[0].id' --output text)

# 创建/events资源
EVENTS_RESOURCE_ID=$(docker exec browse-etl-localstack awslocal apigateway get-resources \
  --rest-api-id "$API_ID" \
  --query "items[?path=='/events'].id" --output text 2>/dev/null || echo "")

if [ -z "$EVENTS_RESOURCE_ID" ]; then
  EVENTS_RESOURCE_ID=$(docker exec browse-etl-localstack awslocal apigateway create-resource \
    --rest-api-id "$API_ID" \
    --parent-id "$ROOT_RESOURCE_ID" \
    --path-part events \
    --region us-east-1 \
    --query 'id' --output text)
  echo "✅ 创建资源: /events"
fi

# 创建POST方法
docker exec browse-etl-localstack awslocal apigateway put-method \
  --rest-api-id "$API_ID" \
  --resource-id "$EVENTS_RESOURCE_ID" \
  --http-method POST \
  --authorization-type NONE \
  --region us-east-1 \
  2>/dev/null || echo "POST方法已存在"

# 集成Lambda
docker exec browse-etl-localstack awslocal apigateway put-integration \
  --rest-api-id "$API_ID" \
  --resource-id "$EVENTS_RESOURCE_ID" \
  --http-method POST \
  --type AWS_PROXY \
  --integration-http-method POST \
  --uri "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:click-event-handler/invocations" \
  --region us-east-1 \
  2>/dev/null || echo "Lambda集成已存在"

# 部署API
docker exec browse-etl-localstack awslocal apigateway create-deployment \
  --rest-api-id "$API_ID" \
  --stage-name local \
  --region us-east-1 \
  >/dev/null 2>&1

echo "✅ API Gateway已部署"

# 输出API端点
API_ENDPOINT="http://localhost:4566/restapis/$API_ID/local/_user_request_/events"

echo ""
echo "=========================================="
echo "✅ 部署完成！"
echo "=========================================="
echo ""
echo "API端点: $API_ENDPOINT"
echo ""
echo "测试命令:"
echo "curl -X POST $API_ENDPOINT \\"
echo "  -H 'Content-Type: application/json' \\"
echo "  -d '{\"userId\":\"user123\",\"eventType\":\"click\",\"timestamp\":$(date +%s)000}'"
echo ""

# 保存API端点到文件
echo "$API_ENDPOINT" > /tmp/browse-etl-api-endpoint.txt

# 清理
rm -rf "$TEMP_DIR"
rm -f /tmp/lambda-function.zip

